import React, {useState} from 'react'

export default function CheckBox() {

    const [checks, setChecks] = useState(
        {
        check: false, 
        children: [
            {
                check: true
            },
            {
                check: false
            },
            {
                check: false
            }
        ]
    });

    const changeCheckBox = (type) => {
       if(type === 'all') {
           const childState = checks.children.map(item=> {return {check: !checks.check}});
           setChecks({...checks, check: !checks.check, children: childState})
       } else {
           const newState = checks.children.map((_,index) => {
               if (index === type) {
                   return { check: ! _.check};
               } else {
                   return _;
               }
           });
           const checkLength = newState.filter(item=> item.check).length;
           const newALLCheck = checkLength === checks.children.length ? true : false;
         
        setChecks({...checks, children: newState, check: newALLCheck});
       }
    }

    return (
        <div>
            <lable>全选</lable>
            <input type="checkbox" onChange={()=> changeCheckBox('all')} checked={checks.check}/>
            <br/>
            <input type="checkbox" onChange={()=> changeCheckBox(0)} checked={checks.children[0].check}/>
            <input type="checkbox" onChange={()=> changeCheckBox(1)} checked={checks.children[1].check}/>
            <input type="checkbox" onChange={()=> changeCheckBox(2)} checked={checks.children[2].check}/>
        </div>
    )
}
